import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with Intellij IDEA
 * Description:
 * User:
 * Date:2022-06-22
 * Time:14:49
 */
public class fileFind {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的文件的路径 (绝对路径 or 相对路径) :");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()) {
            System.out.println("您输入的根目录不存在或许不是目录，退出");
            return;
        }
        System.out.println("您输入要找的文件名中的字符:");
        String token = scanner.next();
        List<File> result = new ArrayList<>();
        scanDirWithContent(rootDir,token,result);
        System.out.println("共找到了符合条件的文件 "+ result.size() + "个，他们分别是");
        for (File file : result) {
            System.out.println(file.getCanonicalPath());
        }
    }

    private static void scanDirWithContent(File rootDir, String token, List<File> result) throws IOException {
        File[] files = rootDir.listFiles();
        if(files == null || files.length == 0) {
            return;
        }
        for(File file : files) {
            if(file.isDirectory()) {
                scanDirWithContent(file,token,result);
            }else {
                if(isContentContains(file,token)) {
                    result.add(file.getAbsoluteFile());
                }
            }
        }
    }

    private static boolean isContentContains(File file, String token) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (InputStream is = new FileInputStream(file)) {
            try (Scanner scanner = new Scanner(is,"UTF-8")){
                while (scanner.hasNextLine()) {
                    sb.append(scanner.nextLine());
                    sb.append("\r\n");
                }
            }
        }
        return sb.indexOf(token) != -1;
    }
}
